package com.work.fairdispatch;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class Worker {

    private static final String TASK_QUEUE_NAME = "task_queue";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        final Connection connection = factory.newConnection();
        final Channel channel = connection.createChannel();
        // 队列是持久化的
        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        // 表示只预抓取一条消息，告诉broker在没有收到消费确认时不再发送消息
        //设置为1会导致消息的公平分配（Fair Dispatch），否则就是轮询方式（Round Robin）
        //Qos:Quality of Service:服务质量
        channel.basicQos(1);

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");

            System.out.println(" [x] Received '" + message + "'");
            try {
                doWork(message);

            } finally {
                System.out.println(" [x] Done");
                //确认消息消费完毕，multiple表示只确认当前的deliverTag代表的消息，否则就是确认所有的消息的消费
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            }
        };
        //autoAck=false表示开启消息消费的手动确认
        channel.basicConsume(TASK_QUEUE_NAME, false, deliverCallback, consumerTag -> {
        });
    }

    private static void doWork(String task) {
        for (char ch : task.toCharArray()) {

            if (ch == '.') {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException _ignored) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}